package com.yiwu.web.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpRequest;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yiwu.common.domain.dto.UserDTO;
import com.yiwu.common.domain.entity.Products;
import com.yiwu.common.domain.entity.UserFavorites;
import com.yiwu.common.domain.entity.Users;
import com.yiwu.common.enums.ResponseCode;
import com.yiwu.common.exception.BusinessException;
import com.yiwu.common.model.WeiXinPhoneResponse;
import com.yiwu.common.model.vo.user.UserCodeReqVO;
import com.yiwu.common.utils.EncryptionUtil;
import com.yiwu.common.utils.JsonUtil;
import com.yiwu.web.service.UserService;
import jakarta.annotation.Resource;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * @version 1.0
 * @description TODO
 * @date 2024/5/23 1:43
 */
@Service
public class UserServiceImpl implements UserService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;


    @Override
    public UserDTO login(UserCodeReqVO userCodeReqVO) {
        //增加限流操作
        try {
            String ack = stringRedisTemplate.opsForValue().get("yiwu-weixin");
            String weixinAddress = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=" + ack;
            String code = JsonUtil.toJsonString(userCodeReqVO);
            String result = HttpRequest.post(weixinAddress)
                    .body(code)
                    .execute().body();

            ObjectMapper objectMapper = new ObjectMapper();
            WeiXinPhoneResponse weiXinPhoneResponse = objectMapper.readValue(result, WeiXinPhoneResponse.class);
            if (weiXinPhoneResponse.getErrcode() != 0) {
                throw new BusinessException(ResponseCode.LOGIN_ERROR);
            }
            if (ObjectUtil.isEmpty(weiXinPhoneResponse)) {
                throw new BusinessException(ResponseCode.LOGIN_ERROR);
            }

            Users user = new Users();
            Users users = user.insertOrLogin(weiXinPhoneResponse.getPhone_info().getPhoneNumber());
            String userId = users.getId().toString();
            UserDTO userDTO = new UserDTO();
            BeanUtils.copyProperties(users, userDTO);
            userDTO.setId(userId);
            String encrypt = EncryptionUtil.encrypt(userDTO.getId());
            userDTO.setToken(encrypt);

            QueryWrapper<UserFavorites> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("user_id", userId);
            UserFavorites userFavorites = new UserFavorites();
            Long favoriteCount = userFavorites.selectCount(queryWrapper);
            QueryWrapper<Products> productsQueryWrapper = new QueryWrapper<>();
            productsQueryWrapper.eq("seller_id", userId);
            productsQueryWrapper.eq("pstatus", 0);
            Products products = new Products();
            Long productCount = products.selectCount(productsQueryWrapper);

            userDTO.setFavoriteCount(favoriteCount);
            userDTO.setProductCount(productCount);

            stringRedisTemplate.opsForValue().set(userId + "yiwu-favoriteCount", favoriteCount.toString(), 7, TimeUnit.DAYS);
            stringRedisTemplate.opsForValue().set(userId + "yiwu-productCount", productCount.toString(), 7, TimeUnit.DAYS);
            stringRedisTemplate.opsForValue().set(encrypt + "yiwu", userId.toString(), 7, TimeUnit.DAYS);

            return userDTO;
        } catch (Exception e) {
            throw new BusinessException(ResponseCode.LOGIN_ERROR);
        }

    }

}
